/**
 * 
 */
package com.org.cbs.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.org.cbs.model.UserDemo;

/**
 * @className UserDemoImpl
 * @author zhengguohui
 * @description
 * @date 2018年7月6日
 */
public class UserDemoImpl implements UserDemoDao {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public List<UserDemo> findAll() {
		return this.mongoTemplate.find(new Query(), UserDemo.class);
	}

	@Override
	public List<UserDemo> findList(int skip, int limit) {
		Query query = new Query();
		query.with(new Sort((List<Order>) new Order(Direction.ASC, "_id")));
		query.skip(skip).limit(limit);
		return this.mongoTemplate.find(query, UserDemo.class);
	}

	@Override
	public void store(UserDemo user) {
		mongoTemplate.save(user);
	}

	/**
	 * Criteria.where("username").is(username) 前一个是数据库的字段,后一个是java类的字段
	 *
	 * @param username
	 * @return
	 */
	@Override
	public UserDemo findOneByUsername(String username) {
		Query query = new Query();
		Criteria criteria = Criteria.where("username").is(username);
		query.addCriteria(criteria);
		return this.mongoTemplate.findOne(query, UserDemo.class);
	}

	@Override
	public UserDemo findOne(String id) {
		Query query = new Query();
		Criteria criteria = Criteria.where("_id").is(id);
		query.addCriteria(criteria);
		return this.mongoTemplate.findOne(query, UserDemo.class);
	}

	@Override
	public void updateFirst(UserDemo user) {
		Update update = new Update();
		Query query = new Query();
		update.set("username", user.getUsername());
		update.set("password", user.getPwd());
		this.mongoTemplate.updateFirst(query.addCriteria(Criteria.where("_id").is(user.getId())), update,
				UserDemo.class);
	}

	@Override
	public void delete(String... ids) {
		if (ids == null || ids.length == 0) {
			return;
		}
		for (String id : ids) {
			Query query = new Query(Criteria.where("_id").is(id));
			this.mongoTemplate.remove(query, UserDemo.class);
		}
	}
}
